package com.ygk.bluepath.core;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.widget.Toast;

import com.lidroid.xutils.DbUtils;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.EScenarioType;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengRegistrar;
import com.umeng.message.entity.UMessage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


import cn.smssdk.SMSSDK;
import utils.DatabaseUtil;
import utils.Inf;
import utils.LogUtils;
import utils.SharedPreUtil;
public class BApp extends Application {
    // TODO Remove unused code found by UCDetector
    // static final String TAG = "IdouApp";

    private String RootDir = Environment.getExternalStorageDirectory()
            .getPath() + "/YGK/BluePath/";
    private String mPicCache = RootDir + "mPicCache/";
    private String saveDir = mPicCache + "Photos/myimage/";
    private String dBCache = RootDir + "DbCache/";
    private String[] path = {RootDir, mPicCache,saveDir,dBCache};

    private static BApp mApplication;
    private SharedPreUtil sp;
    private ImageLoader mImageLoader;


    public DbUtils locationDbCache;
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub

        super.onCreate();
        mApplication = this;

        initImageLoader(this);
        initpath();
        initUMeng();



    }



    private void initUMeng() {
        // TODO Auto-generated method stub


        //友盟统计初始
        MobclickAgent.setScenarioType(getApplicationContext(), EScenarioType.E_UM_NORMAL);

        PushAgent mPushAgent = PushAgent.getInstance(getApplicationContext());
        mPushAgent.setDebugMode(LogUtils.DEBUG);

        //禁用默认的页面统计
        MobclickAgent.openActivityDurationTrack(false);

        //开启推送服务
        mPushAgent.enable();

        if (mPushAgent.isEnabled()) {
            String device_token = UmengRegistrar.getRegistrationId(getApplicationContext());
            getSharedPreUtil().setDeviceToken(device_token);
            LogUtils.i("device_token::--" + device_token);
        } else {
            LogUtils.i("device_token:isNotEnabled()");
        }
        //关闭客户端的通知服务。
        //mPushAgent.disable();
        //来查询状态
        //mPushAgent.isEnabled();

        //自定义消息
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
               tt( msg.custom);
            }
        };
        mPushAgent.setMessageHandler(messageHandler);

    }


    public synchronized static BApp getInstance() {
        return mApplication;
    }

    private void initpath() {
        // TODO Auto-generated method stub
        for (int i = 0; i < path.length; i++) {
            File file = new File(path[i]);
            if (!file.exists()) {
                file.mkdirs();
            }
        }

    }

    public SharedPreUtil getSharedPreUtil() {
        // TODO Auto-generated method stub

        if (sp == null) {
            sp = new SharedPreUtil(this, "AbSys");
        }
        return sp;
    }

    public String getRoot() {
        // TODO Auto-generated method stub

        return RootDir;
    }

    public String getmPicCache() {
        // TODO Auto-generated method stub

        return mPicCache;
    }
    public DbUtils locationDb;
    public DbUtils getLocationDB() {
        if (locationDb == null) {
            locationDb= DatabaseUtil.getDb(this,dBCache, "LocationRecordDB.db", Inf.DbRecordVersion,"bean_LocationBean");
        }
        LogUtils.i("locationDb:" + (locationDb == null));
        return locationDb;
    }


    // ----------------------------------------------------------------------------------

    public void tt(final String tt) {
        // TODO Auto-generated method stub
        new Handler(getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), tt, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private List<Activity> list = new ArrayList<Activity>();

    public void addActivity(Activity activity) {

        if (!list.contains(activity)) {
            list.add(activity);
        }

    }

    public void removeActivity(Activity activity) {

        if (list.contains(activity)) {
            list.remove(activity);
        }

    }

    public void finish() {

        //用来保存统计数据
        MobclickAgent.onKillProcess(getApplicationContext());

        for (Activity activity : list) {
            if (activity != null) {
                activity.finish();
            }
        }

        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
    }


    public ImageLoader getmImageLoader() {
        return mImageLoader;
    }

    public void setmImageLoader(ImageLoader mImageLoader) {
        this.mImageLoader = mImageLoader;
    }

    /**
     * 初始化ImageLoader
     */
    public void initImageLoader(Context context) {
        File cacheDir = StorageUtils
                .getOwnCacheDirectory(context, mPicCache + "");// 获取到缓存的目录地址
        // 创建配置ImageLoader(所有的选项都是可选的,只使用那些你真的想定制)，这个可以设定在APPLACATION里面，设置为全局的配置参数
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context)
                // 线程池内加载的数量
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCacheExtraOptions(480, 800)
                .memoryCache(new WeakMemoryCache())
                .denyCacheImageMultipleSizesInMemory()
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCache(new UnlimitedDiscCache(cacheDir))
                // .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .imageDownloader(
                        new BaseImageDownloader(context, 15 * 1000, 50 * 1000))
                .writeDebugLogs() // Remove for release app
                .build();
        // Initialize ImageLoader with configuration.
        mImageLoader = ImageLoader.getInstance();
        mImageLoader.init(config);// 全局初始化此配置
    }

}